<!--
  API日志详情组件
  @description 查看API日志的详细信息，包含请求和响应数据
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1200px" :scroll="true" max-height="700px">
    <div v-loading="loading">
      <!-- 基本信息 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('sop.apiLog.basicInfo') }}</span>
          </div>
        </template>
        <el-descriptions :column="3" border v-if="logData">
          <el-descriptions-item :label="t('sop.apiLog.traceId')">
            <el-text class="trace-id-text" copyable>{{ logData.traceId }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.appId')">
            <el-text class="app-id-text" copyable>{{ logData.appId }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.merchantNo')">
            {{ logData.merchantNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.httpMethod')">
            <el-tag :type="getHttpMethodTagType(logData.httpMethod)">
              {{ logData.httpMethod }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.apiPath')">
            {{ logData.apiPath }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.responseCode')">
            <el-tag :type="getResponseCodeTagType(logData.responseCode)">
              {{ logData.responseCode }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.responseTime')">
            <span :class="getResponseTimeClass(logData.responseTime)">
              {{ logData.responseTime }}ms
            </span>
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.clientIp')">
            {{ logData.clientIp }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.userAgent')">
            {{ logData.userAgent || '-' }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.requestTime')">
            {{ formatDate(logData.requestTime) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('sop.apiLog.responseTime')">
            {{ formatDate(logData.responseTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 请求信息 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('sop.apiLog.requestInfo') }}</span>
            <el-button
              type="primary"
              size="small"
              @click="copyRequestData"
            >
              <Icon class="mr-5px" icon="ep:copy-document" />
              {{ t('sop.apiLog.copyRequest') }}
            </el-button>
          </div>
        </template>
        
        <!-- 请求头 -->
        <div class="mb-15px" v-if="logData?.requestHeaders">
          <div class="section-title">{{ t('sop.apiLog.requestHeaders') }}</div>
          <el-input
            v-model="formattedRequestHeaders"
            type="textarea"
            :rows="6"
            readonly
            class="json-textarea"
          />
        </div>
        
        <!-- 请求参数 -->
        <div class="mb-15px" v-if="logData?.requestParams">
          <div class="section-title">{{ t('sop.apiLog.requestParams') }}</div>
          <el-input
            v-model="formattedRequestParams"
            type="textarea"
            :rows="8"
            readonly
            class="json-textarea"
          />
        </div>
        
        <!-- 请求体 -->
        <div v-if="logData?.requestBody">
          <div class="section-title">{{ t('sop.apiLog.requestBody') }}</div>
          <el-input
            v-model="formattedRequestBody"
            type="textarea"
            :rows="10"
            readonly
            class="json-textarea"
          />
        </div>
      </el-card>
      
      <!-- 响应信息 -->
      <el-card>
        <template #header>
          <div class="card-header">
            <span>{{ t('sop.apiLog.responseInfo') }}</span>
            <el-button
              type="primary"
              size="small"
              @click="copyResponseData"
            >
              <Icon class="mr-5px" icon="ep:copy-document" />
              {{ t('sop.apiLog.copyResponse') }}
            </el-button>
          </div>
        </template>
        
        <!-- 响应头 -->
        <div class="mb-15px" v-if="logData?.responseHeaders">
          <div class="section-title">{{ t('sop.apiLog.responseHeaders') }}</div>
          <el-input
            v-model="formattedResponseHeaders"
            type="textarea"
            :rows="6"
            readonly
            class="json-textarea"
          />
        </div>
        
        <!-- 响应体 -->
        <div v-if="logData?.responseBody">
          <div class="section-title">{{ t('sop.apiLog.responseBody') }}</div>
          <el-input
            v-model="formattedResponseBody"
            type="textarea"
            :rows="12"
            readonly
            class="json-textarea"
          />
        </div>
        
        <!-- 错误信息 -->
        <div v-if="logData?.errorMessage">
          <div class="section-title error-title">{{ t('sop.apiLog.errorMessage') }}</div>
          <el-alert
            :title="logData.errorMessage"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/formatTime'
import { getApiLogApi } from '@/api/sop/apiLog'
import type { ApiLogVO } from '@/api/sop/types'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'

defineOptions({ name: 'ApiLogDetail' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loading = ref(false)

// 日志数据
const logData = ref<ApiLogVO>()

// 格式化的数据
const formattedRequestHeaders = computed(() => {
  return formatJson(logData.value?.requestHeaders)
})

const formattedRequestParams = computed(() => {
  return formatJson(logData.value?.requestParams)
})

const formattedRequestBody = computed(() => {
  return formatJson(logData.value?.requestBody)
})

const formattedResponseHeaders = computed(() => {
  return formatJson(logData.value?.responseHeaders)
})

const formattedResponseBody = computed(() => {
  return formatJson(logData.value?.responseBody)
})

/**
 * 打开对话框
 */
const open = async (log: ApiLogVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('sop.apiLog.detail') + ' - ' + log.traceId
  loading.value = true
  
  try {
    // 获取日志详情
    const data = await getApiLogApi(log.id)
    logData.value = data
  } catch (error) {
    console.error('获取API日志详情失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 格式化JSON
 */
const formatJson = (data: any) => {
  if (!data) return ''
  try {
    if (typeof data === 'string') {
      return JSON.stringify(JSON.parse(data), null, 2)
    }
    return JSON.stringify(data, null, 2)
  } catch (error) {
    return data.toString()
  }
}

/**
 * 复制请求数据
 */
const copyRequestData = async () => {
  if (!logData.value) return
  
  const requestData = {
    method: logData.value.httpMethod,
    url: logData.value.apiPath,
    headers: logData.value.requestHeaders,
    params: logData.value.requestParams,
    body: logData.value.requestBody
  }
  
  try {
    await navigator.clipboard.writeText(JSON.stringify(requestData, null, 2))
    ElMessage.success(t('sop.apiLog.tips.copySuccess'))
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error(t('sop.apiLog.tips.copyFailed'))
  }
}

/**
 * 复制响应数据
 */
const copyResponseData = async () => {
  if (!logData.value) return
  
  const responseData = {
    code: logData.value.responseCode,
    headers: logData.value.responseHeaders,
    body: logData.value.responseBody,
    error: logData.value.errorMessage
  }
  
  try {
    await navigator.clipboard.writeText(JSON.stringify(responseData, null, 2))
    ElMessage.success(t('sop.apiLog.tips.copySuccess'))
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error(t('sop.apiLog.tips.copyFailed'))
  }
}

// 标签类型获取函数
const getHttpMethodTagType = (method: string) => {
  const methodMap = {
    'GET': 'primary',
    'POST': 'success',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return methodMap[method] || ''
}

const getResponseCodeTagType = (code: number) => {
  if (code >= 200 && code < 300) return 'success'
  if (code >= 300 && code < 400) return 'info'
  if (code >= 400 && code < 500) return 'warning'
  if (code >= 500) return 'danger'
  return ''
}

const getResponseTimeClass = (time: number) => {
  if (time < 100) return 'fast-response'
  if (time < 500) return 'normal-response'
  if (time < 1000) return 'slow-response'
  return 'very-slow-response'
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.mb-20px {
  margin-bottom: 20px;
}

.mb-15px {
  margin-bottom: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trace-id-text {
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

.app-id-text {
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.error-title {
  color: #f56c6c;
}

.json-textarea {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.json-textarea :deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
}

.fast-response {
  color: #67c23a;
  font-weight: bold;
}

.normal-response {
  color: #409eff;
}

.slow-response {
  color: #e6a23c;
  font-weight: bold;
}

.very-slow-response {
  color: #f56c6c;
  font-weight: bold;
}
</style>
